import { readDir } from '../common/util'
import chalk from 'chalk'
import { getComponents, upload } from './api'
import linq from 'linq'
import config from './config'

const main = async () => {
  console.log(chalk.blueBright(`\n start task . `))
  //读取本地文件
  const packages = readDir(config.readDir, '.tgz');
  console.log(`本地路径中读取到${packages.length}个包。`)
  console.log(`将本地包转换成数组以便差量化上传.`)
  const packageInfos = linq.from(packages).select((path) => {
    const tempArray = path.split('\\')
    const fileName = tempArray[tempArray.length - 1];
    const packageName = fileName.substring(0, fileName.replace(/.tgz/g, '').lastIndexOf('-'));
    const version = fileName.replace(/.tgz/g, '').substring(fileName.lastIndexOf('-') + 1);
    return {
      filePath: path,
      fileName: fileName,
      name: packageName,
      version: version
    }
  }).toArray();
  console.log(`转换完成.`)
  // 获取组件列表
  let components = []
  console.log(`开始调用api获取组件列表`)


  //递归调用

  let continuationToken = ''
  while (continuationToken !== null) {
    await getComponents(config.registry, continuationToken).then((res) => {
      components = components.concat(res.items)
      console.log(`在nexus中获取到个${components.length}包。`)
      continuationToken = res.continuationToken
    }).catch(e => {
      console.log(e);
    })
  }

  console.log(`接口调用完成共获取到，${components.length}包。`)
  const notUploadPacks = linq.from(packageInfos).where(q => linq.from(components).any(c => c.name === q.name && c.version === q.version) === false).toArray();
  console.log(`本次任务数${notUploadPacks.length}`);
  for (let index = 0; index < notUploadPacks.length; index++) {
    const item = notUploadPacks[index];
    console.log(chalk.blueBright(`\n begin task ${index + 1}/${notUploadPacks.length} ${item.fileName}`))
    try {
      await upload(config.registry, item.filePath, item.fileName, "npm.asset").then(() => {
        console.log(chalk.blueBright(`\n finished task ${index + 1}/${notUploadPacks.length} ${item.fileName}`))
      }).catch(e => {

      })
    } catch (error) {
      console.log(e)
    }
  }


  console.log(chalk.blueBright(`\n all task finished . `))
}
main()
